package com.heima.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.service.CommentHotService;
import com.heima.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {


    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Autowired
    CommentHotService commentHotService;

    /**
     * 评论保存
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //  1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //  校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录");
        }
        // 校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
        //    2. 阿里云校验评论内容是否违规
        boolean scan = handleTextScan(dto.getContent());
        if (!scan) {
            // (简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //    3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        ApUser apUser = result.getData();
        ApComment apComment = new ApComment();
        BeanUtils.copyProperties(apUser, apComment);
        //   4. 创建评论信息，并保存到mongo

        apComment.setAuthorId(user.getId());
        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        //保存结果
        mongoTemplate.save(apComment);

        //评论行为消息发送

        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));

        //封装 返回
        return ResponseResult.okResult(apComment);
    }


    /**
     * 评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //   1. 参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数不能为空");
        }
        //   评论id不能为空  operation必须为 0  或  1  (注解校验)
        //  2. 根据评论id查询评论数据， 为null返回错误信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        RLock lock = redissonClient.getLock("likes-lock");
        lock.lock();
        ApComment apComment;
        try {
            Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
            ApCommentLike apCommentLike = mongoTemplate.findOne(query, ApCommentLike.class);
            //  3. 如果是点赞操作 判断是否已经点赞

            Query query1 = Query.query(Criteria.where("id").is(dto.getCommentId()));
            apComment = mongoTemplate.findOne(query1, ApComment.class);
            if (dto.getOperation() == 0) {

                if (apCommentLike == null) {
                    //   未点过赞   保存点赞信息到mongo
                    ApCommentLike comment = new ApCommentLike();
                    comment.setCommentId(dto.getCommentId());
                    comment.setOperation(dto.getOperation());
                    comment.setAuthorId(user.getId());
                    mongoTemplate.save(comment);
                    //   并修改评论信息的点赞数量( + 1)
                    Integer i = apComment.getLikes() + 1;
                    Update update = new Update();
                    update.set("likes", i).set("createdTime", new Date());
                    mongoTemplate.updateMulti(query1, update, ApComment.class);
                    apComment.setLikes(i);
                    commentHotService.hotCommentExecutor(apComment);
                } else {
                    //  点过赞提示 请勿重复点赞
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
                }
            } else {
                //   4. 如果是取消点赞操作
                //         删除点赞信息
                mongoTemplate.remove(query, ApCommentLike.class);
                //    并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                Integer likes = apComment.getLikes();
                if (likes >= 1) {
                    Integer i = likes - 1;
                    Update update = new Update();
                    update.set("likes", i);
                    mongoTemplate.updateMulti(query1, update, ApComment.class);
                    apComment.setLikes(i);
                    commentHotService.hotCommentExecutor(apComment);
                }
                //  5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
            }
        } finally {
            lock.unlock();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 评论列表显示功能实现
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //  1. 参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }

        //  2. 根据条件查询评论列表
        List<ApComment> apCommentList = null;
        if (dto.getIndex().intValue() == 1) {
            //查询评论热点集合
            Query query = Query.query(Criteria.where("flag").is(1).and("articleId").is(dto.getArticleId()))
                    .with(Sort.by(Sort.Direction.DESC, "likes")).limit(5);
            apCommentList = mongoTemplate.find(query, ApComment.class);
            //查询普通评论
            int size = dto.getSize() - apCommentList.size();
            Query query1 = Query.query(Criteria.where("flag").is(0).and("articleId").is(dto.getArticleId()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                    .limit(size);
            List<ApComment> apCommentList1 = mongoTemplate.find(query1, ApComment.class);

            apCommentList.addAll(apCommentList1);
        } else {
            //直接返回普通评论
            Query query1 = Query.query(Criteria.where("flag").is(0).and("articleId").is(dto.getArticleId()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                    .with(PageRequest.of(dto.getIndex() - 1, dto.getSize()));
            apCommentList = mongoTemplate.find(query1, ApComment.class);
        }

        //3. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //   4. 如果未登录直接返回评论列表
        if (user == null) {
            return ResponseResult.okResult(apCommentList);
        }
//        //   4. 如果未登录直接返回评论列表
        List<ApCommentVo> apCommentVos = new ArrayList<>();

//
        //    5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
        List<ApCommentLike> likeList = mongoTemplate.findAll(ApCommentLike.class);
        for (ApComment commentVo : apCommentList) {
            //  commentId  in    评论id列表   authorId = 登录人id
            ApCommentVo apCommentVo = new ApCommentVo();
            //  (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
            BeanUtils.copyProperties(commentVo, apCommentVo);
            //apCommentVos.add(apCommentVo);
            for (ApCommentLike apCommentLike : likeList) {
                if (commentVo.getAuthorId().equals(user.getId()) && apCommentLike.getCommentId().equals(commentVo.getId())) {
                    //   其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
                    apCommentVo.setOperation((short) 0);
                }
            }
            apCommentVos.add(apCommentVo);
        }
        return ResponseResult.okResult(apCommentVos);
    }

    /**
     * 阿里云文本审核
     *
     * @param content
     * @return
     */
    private boolean handleTextScan(String content) {
        boolean flag = true;
        //
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    flag = false;
                    break;
                case "review":
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}", e.getMessage());
        }
        return flag;
    }
}
